package chatclient.applets.components;


import chatclient.applets.canvas.ImageCanvas;
import java.awt.Image;
import java.awt.event.*;
import java.util.Enumeration;
import java.util.Vector;

public class Button extends ImageCanvas
        implements MouseListener {

    public Button(Image image, Image image1, Image image2) {
        super(image, 1, 1);
        released = image;
        pressed = image1;
        hovered = image2 != null ? image2 : image;
        listeners = new Vector();

        addMouseListener(this);
    }

    private void lockListeners(boolean flag) {
        synchronized (listeners) {
            listenersLocks++;
            if (flag && newListeners == null) {
                newListeners = (Vector) listeners.clone();
            }
        }
    }

    private void unlockListeners() {
        synchronized (listeners) {
            if (--listenersLocks == 0 && newListeners != null) {
                listeners = newListeners;
            }
        }
    }

    public void addActionListener(ActionListener actionlistener) {
        lockListeners(true);
        if (!newListeners.contains(actionlistener)) {
            newListeners.addElement(actionlistener);
        }
        unlockListeners();
    }

    public void removeActionListener(ActionListener actionlistener) {
        lockListeners(true);
        if (newListeners.contains(actionlistener)) {
            newListeners.removeElement(actionlistener);
        }
        unlockListeners();
    }

    public void mouseClicked(MouseEvent mouseevent) {
        ActionEvent actionevent = new ActionEvent(this, 1001, "", mouseevent.getModifiers());
        lockListeners(false);
        for (Enumeration enumeration = listeners.elements(); enumeration.hasMoreElements(); ((ActionListener) enumeration.nextElement()).actionPerformed(actionevent));
        unlockListeners();
        setImage(released);
        repaint();
    }

    public void mouseEntered(MouseEvent mouseevent) {
        setImage(hovered);
        repaint();
    }

    public void mouseExited(MouseEvent mouseevent) {
        setImage(released);
        repaint();
    }

    public void mousePressed(MouseEvent mouseevent) {
        setImage(pressed);
        repaint();
    }

    public void mouseReleased(MouseEvent mouseevent) {
        setImage(hovered);
        repaint();
    }
    private Vector listeners;
    private Vector newListeners;
    private int listenersLocks;
    private Image released;
    private Image pressed;
    private Image hovered;
}
